package com.wnxy.sdd.redis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class RedisTest02 {
    // 注入对象
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test01(){
        // 存储数据
        redisTemplate.opsForValue().set("person",new Person(100,"张三"));
        // 查看默认的序列化方式
        RedisSerializer keySerializer = redisTemplate.getKeySerializer();
        RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
        System.out.println("查看默认key序列化方式 = " + keySerializer);
        System.out.println("查看默认value序列化方式 = " + valueSerializer);

        // 获取数据
        Person person = (Person) redisTemplate.opsForValue().get("person");
        System.out.println("person = " + person);
    }

    @Test
    public void test02(){
        // 修改key的序列化方式: 序列化为string
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 修改value的序列化方式：序列化为json
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));

        // 注意：指定key、value的序列化方式后，对象可以不实现可序列化接口
        // 存储数据
        redisTemplate.opsForValue().set("address",new Address(100,"广州"));
    }
}
